package cn.my.framework.config.thymeleaf;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.dialect.IDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by zhangl_lc on 2017/8/10.
 */
@Configuration
public class MyThymeleafConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {
    @Value("${spring.thymeleaf.cache:false}")
    boolean cacheable;
    @Value("${spring.thymeleaf.encoding:UTF-8}")
    String encoding;
    @Value("${spring.thymeleaf.suffix:.html}")
    String suffix;
    @Value("${spring.thymeleaf.prefix:classpath:/tpl}")
    String prefix;
    private ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }

    @Bean
    public TemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setEnableSpringELCompiler(true);
        engine.setTemplateResolver(templateResolver());
        Set<IDialect> dialectSet = new HashSet<>();
        dialectSet.add(new ShiroDialect());
        engine.setDialects(dialectSet);
        return engine;
    }

    @Bean
    //@ConfigurationProperties(prefix = "spring.thymeleaf")
    public ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix(prefix);
        resolver.setSuffix(suffix);
        resolver.setCacheable(cacheable);
        resolver.setCharacterEncoding(encoding);
        resolver.setOrder(1);
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }
}
